package com.example.utils;

import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Component
public class CheckCode {
    public void getCheckCode(HttpServletRequest request, HttpServletResponse response){
        //设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");

        //设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);

        int width=100,height=50;
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();//获取画笔对象
        g.setColor(Color.white);//设置画笔颜色
        g.fillRect(0,0,width,height);

        //画边框
        g.setColor(Color.LIGHT_GRAY);
        g.drawRect(0,0,width-1,height-1);
        String code="";
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random=new Random();
        g.setColor(Color.black);
        for(int i=1;i<=4;i++){
            int index=random.nextInt(str.length());
            char ch=str.charAt(index);
            code+=ch;
            //写验证码
            g.drawString(ch+"",width/5*i,height/2);
        }

        //画干扰线
        g.setColor(Color.GREEN);
        for(int i=1;i<10;i++){
            int x1=random.nextInt(width);
            int y1=random.nextInt(height);
            int x2=random.nextInt(width);
            int y2=random.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }
        request.getSession().removeAttribute("code");
        request.getSession().setAttribute("code",code);
        g.dispose();
        try {
            ImageIO.write(image,"jpg",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
